import Vue from "vue";
import { getStitchesByBase64 } from "@/utils/EmbroideryDst.js";
import { writeCanvas } from "@/utils/EmbroideryCanvas.js";
import { colors, Pattern } from "@/utils/EmbroideryPattern.js";

// 字体清单
const resourceFonts = {};
// 正在加载的图片
const resourceImages = {};

// 字体列表
const fontsJson = [
    // { name: "Arial", url: "/fonts/Arial.woff" },
    { name: "Arial", url: "" },
    { name: "Space Age", url: "/fonts-20230202/Space-Age.woff" },
    { name: "Bebas Neue", url: "/fonts-20230202/Bebas-Neue.woff" },
    { name: "Circle", url: "/fonts-20230202/Circle.woff" },
    { name: "Doodle Pen", url: "/fonts-20230202/Doodle-Pen.woff" },
    { name: "Game On", url: "/fonts-20230202/Game-On.woff" },
    { name: "KG Happy", url: "/fonts-20230202/KG-Happy.woff" },
    { name: "Lcd", url: "/fonts-20230202/Lcd.woff" }, // 本地node渲染不出来，但是线上的node能渲染
    { name: "Miss Stanfort", url: "/fonts-20230202/Miss-Stanfort.woff" },
    {
        name: "UniDream LED Regular",
        url: "/fonts-20230202/UniDream-LED-Regular.woff",
    },
];

// 检查某字体是否已安装
const isSupportFontFamily = function (name) {
    if (typeof name != "string") {
        return false;
    }
    let refer = "serif";
    if (name.toLowerCase() == refer.toLowerCase()) {
        return true;
    }
    let text = "a";
    let fontsize = 100;
    let width = 100;
    let height = 100;
    let canvas = document.createElement("canvas");
    let ctx = canvas.getContext("2d", { willReadFrequently: true });

    canvas.width = width;
    canvas.height = height;
    ctx.textAlign = "center";
    ctx.fillStyle = "black";
    ctx.textBaseline = "middle";

    let getData = function (name) {
        ctx.clearRect(0, 0, width, height);
        ctx.font = fontsize + "px " + name + ", " + refer;
        ctx.fillText(text, width / 2, height / 2);
        let data = ctx.getImageData(0, 0, width, height).data;
        return [].slice.call(data).filter((l) => l != 0);
    };

    return getData(refer).join("") !== getData(name).join("");
};

// 获取图片链接
const getImageUri = (url, option = {}) => {
    const types = "simple|print|fastest".split("|");
    const type = types.indexOf(option.type) >= 0 ? option.type : "print";
    const form = option.form || "";

    if (form == "materials") {
        // 最快的图片，选择缩略图时
        url = url.replace(/\.(png|jpe?g|gif)$/i, "-litimg.$1");

        if (type == "fastest") {
            return Vue.prototype.$getImageUrl(url, "medium");
        } else if (type == "simple") {
            return Vue.prototype.$getImageUrl(url, "largest");
        } else {
            return Vue.prototype.$getImageUrl(url, "largest");
        }
    } else {
        // 大图
        return Vue.prototype.$getImageUrl(url, "largest");
    }
};

// 获取缓存图片
export const getImageByCache = (url, option) => {
    let uri = getImageUri(url, option);
    let imagesItem = resourceImages[uri];
    if (imagesItem && imagesItem.status == "complete") {
        return imagesItem.image;
    } else {
        return null;
    }
};

// 加载资源
export const loadImage = (url, option) => {
    let uri = getImageUri(url, option);
    let imagesItem = resourceImages[uri];

    if (!uri) {
        // 没有图片
        return Promise.reject("not url");
    } else if (imagesItem && imagesItem.status == "complete") {
        // 已经有图片了，加载已完成
        return Promise.resolve(imagesItem.image);
    } else if (imagesItem && imagesItem.status == "loading") {
        // 加载中的
        return new Promise((resolve, reject) => {
            imagesItem.callback.push((err) => {
                if (imagesItem.image) {
                    resolve(imagesItem.image);
                } else {
                    reject(err);
                }
            });
        });
    } else {
        // 没有图片
        // 或是图片加载失败
        const loading = {
            count: 10, // 加载次数
            image: null,
            uri: uri,
            status: "loading",
            callback: [],
        };

        const createImage = () => {
            const img = new Image();
            img.onload = () => {
                loading.image = img;
                loading.status = "complete";
                loading.callback.map((cb) => cb(img));
                loading.callback = [];
            };
            img.onerror = (err) => {
                loading.count -= 1;
                if (loading.count > 0) {
                    setTimeout(createImage, 500);
                } else {
                    // 加载多次都失败了
                    loading.status = "error";
                    loading.callback.map((cb) => cb(err));
                    loading.callback = [];
                }
            };
            img.crossOrigin = "anonymous";
            img.src = loading.uri;
        };

        return new Promise((resolve, reject) => {
            loading.callback.push((err) => {
                if (loading.image) {
                    resolve(loading.image);
                } else {
                    reject(err);
                }
            });
            resourceImages[uri] = loading;
            createImage();
        });
    }
};

// 设置缓存
export const setImageCache = (url, image) => {
    // 缩小图片
    const getImage = (image) => {
        // 已经处理了
        return Promise.resolve(image);

        // if(image.width + image.height > 2000){

        //     return new Promise((resolve,reject)=>{

        //         // 太大
        //         const scale = Math.min(1000/image.width,1000/image.height);
        //         const canvas = document.createElement('canvas');
        //         const ctx = canvas.getContext("2d");
        //         const thumb = new Image();

        //         canvas.width = image.width * scale;
        //         canvas.height = image.height * scale;

        //         ctx.drawImage(image,0,0,image.width,image.height,0,0,canvas.width,canvas.height);

        //         thumb.onload = e=>resolve(thumb);
        //         thumb.onerror = e=>reject(e);

        //         thumb.crossOrigin = 'anonymous';
        //         thumb.src = canvas.toDataURL();

        //     });

        // }else{
        //     return Promise.resolve(image)
        // }
    };

    const setCache = (uri, image) => {
        // data/zx/design/nologin/Lion.jpg original https://img.podpartner.com/data/zx/design/nologin/Lion.jpg?x-oss-process=image/format,webp
        // data/zx/design/nologin/Lion.jpg large https://img.podpartner.com/data/zx/design/nologin/Lion.jpg?x-oss-process=image/resize,w_800/format,webp
        // resourceImages

        if (!resourceImages[uri]) {
            resourceImages[uri] = {
                count: 10, // 加载次数
                image: image,
                uri: uri,
                status: "complete",
                callback: [],
            };
        } else {
            const loading = resourceImages[uri];
            loading.image = image;
            loading.status = "complete";
            loading.callback.map((cb) => cb(image));
            loading.callback = [];
        }
    };

    if (!url) {
        // 没有链接
        return Promise.reject();
    } else if (!image) {
        // 没有图片，不操作
        return Promise.reject();
    } else {
        return getImage(image).then((thumb) => {
            const simple = getImageUri(url, {
                type: "simple",
                form: "materials",
            });
            const print = getImageUri(url, {
                type: "print",
                form: "materials",
            });

            setCache(simple, thumb);
            setCache(print, thumb);
            return Promise.resolve(thumb);
        });
    }
};

// 获取图片路径
export const loadFont = (name) => {
    let fontItem = resourceFonts[name];
    let fontSelect = fontsJson.filter((i) => i.name == name)[0];

    if (!name) {
        // 没有字体
        return Promise.resolve();
    } else if (!fontSelect) {
        return Promise.reject("unknown font family");
    } else if (fontItem && fontItem.status == "complete") {
        // 已经有图片了，加载已完成
        return Promise.resolve(fontItem);
    } else if (fontItem && fontItem.status == "loading") {
        // 加载中的
        return new Promise((resolve, reject) => {
            fontItem.callback.push((err) => {
                if (fontItem.status == "complete") {
                    resolve(fontItem);
                } else {
                    reject(err);
                }
            });
        });
    } else {
        return new Promise((resolve, reject) => {
            // 没有图片
            // 或是图片加载失败
            const loader = {
                count: 10, // 加载次数
                name: fontSelect.name,
                uri: fontSelect.url,
                status: "loading",
                callback: [
                    (err) => {
                        if (loader.status == "complete") {
                            resolve(loader);
                        } else {
                            reject(err);
                        }
                    },
                ],
            };

            const createFont = () => {
                // 超时时间
                let timeout = 5000;
                let beginTime = new Date().getTime();
                let style = document.createElement("style");
                let tpl =
                    "@font-face {font-family:[name];src:url([url]);font-display: swap}";

                style.type = "text/css";
                style.innerText = tpl
                    .replace("[name]", fontSelect.name)
                    .replace(
                        "[url]",
                        Vue.prototype.$getStaticUrl(fontSelect.url)
                    );
                document.head.appendChild(style);

                let checkReady = () => {
                    let ready = isSupportFontFamily(fontSelect.name);
                    let overTime = new Date().getTime();

                    if (ready) {
                        // 完成
                        loader.status = "complete";
                        loader.callback.map((cb) => cb(loader));
                        loader.callback = [];
                    } else if (overTime - beginTime > timeout) {
                        // 失败
                        loader.count -= 1;
                        if (loader.count > 0) {
                            setTimeout(createFont, 500);
                        } else {
                            // 加载多次都失败了
                            loader.status = "error";
                            loader.callback.map((cb) => cb("load fail"));
                            loader.callback = [];
                        }
                    } else {
                        // 循环松紧度
                        setTimeout(checkReady, 500);
                    }
                };
                checkReady();
            };

            resourceFonts[name] = loader;

            if (fontSelect.url) {
                createFont();
            } else {
                loader.status = "complete";
                loader.callback.map((cb) => cb(loader));
                loader.callback = [];
            }
        });
    }
};

// 加载所有字体
export const loadAllFont = () => {
    const promises = fontsJson.map((item) => loadFont(item.name));
    return Promise.all(promises);
};

// 获取字体状态
export const getFontByCache = (name) => {
    let fontItem = resourceFonts[name];
    if (fontItem && fontItem.status == "complete") {
        return fontItem;
    } else {
        return null;
    }
};

// 加载版带
export const loadEmb = (layer) => {
    const codes = (layer.line_color || "").split(",");
    const list = codes.map((i) => colors.find((c) => c.code == i));
    const exist = list.filter((i) => i);
    const stitches = getStitchesByBase64(layer.stitches);

    const canvas = writeCanvas(stitches, exist, {
        width: layer.dst_width,
        height: layer.dst_height,
    });
    return canvas;
};

// 清空缓存
export const cleanup = (name) => {
    Object.keys(resourceFonts).map((key) => {
        delete resourceFonts[key];
    });

    Object.keys(resourceImages).map((key) => {
        delete resourceImages[key];
    });
};

export default {
    fontsJson,
    loadImage,
    setImageCache,
    getImageByCache,
    loadFont,
    loadAllFont,
    getFontByCache,
    loadEmb,
    cleanup,
};
